/*
 * Copyright (c) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { ts, NodePredicate } from "qvog-dsl";
import { native, HomeCheckHint } from "qvog-dsl";

const SEVERITY = 2;
const DOC_PATH = '';
const DESCRIPTION = 'Use \'namespace\' instead of \'module\' to declare custom TypeScript modules.';


export const ModuleDeclaration: NodePredicate<ts.ModuleDeclaration> = {
    is(node: ts.Node): node is ts.ModuleDeclaration {
        return ts.isModuleDeclaration(node);
    },
};

export default native<HomeCheckHint>()()
    .match(ModuleDeclaration)
    .when((node: ts.ModuleDeclaration): boolean => {
        return processModuleDeclaration(node, false);
    })
    .report({
        severity: SEVERITY,
        description: DESCRIPTION,
        docPath: DOC_PATH,
    });

function processModuleDeclaration(node: ts.ModuleDeclaration, moduleBlock: boolean): boolean {
    const isInternalModule = ts.isIdentifier(node.name); // 内部模块名称是标识符
    const isExternalModule = ts.isStringLiteral(node.name); // 外部模块名称是字符串字面量
    if (isExternalModule) {// 外部模块声明，不需要处理
        return false;
    };
    if (isInternalModule) {
        let text = node.getText();
        if (moduleBlock) {
            text = node.getFullText();
        };
        if (ts.isModuleDeclaration(node) || moduleBlock) {
            const moduleTokens = Array.from(node.getChildren());
            const moduleKeywordNode = moduleTokens.find(token =>
                token.kind === ts.SyntaxKind.ModuleKeyword
            );
            if (moduleKeywordNode && moduleKeywordNode.getText() === 'module') {
                // 创建缺陷报告和修复建议
                return true;
            };
        };
    };
    // 递归处理嵌套的模块声明
    if (node.body && ts.isModuleBlock(node.body)) {
        for (const statement of node.body.statements) {
            if (!ts.isModuleDeclaration(statement)) {
                continue;
            };
            if (processModuleDeclaration(statement as ts.ModuleDeclaration, true)) {
                return true;
            }
        };
    };
    return false;
};